package org.capybara.coffeehouse.device;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.capybara.coffeehouse.event.Event;
import org.capybara.coffeehouse.event.TurnOffEvent;
import org.capybara.coffeehouse.event.TurnOnEvent;

/**
 * Basic API for a button.
 * @author dfraser
 *
 */
public class Switch extends Device {
	
	public Switch() {
		ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
		scheduledThreadPoolExecutor.scheduleAtFixedRate(new Clicky(this), 2000, 10000, TimeUnit.MILLISECONDS);
	}
	
	@Override
	public String getName() {
		return "switch";
	}
	
	public void turnOn() {
		// send an event
		Event e = new TurnOnEvent(this);
		fireEvent(e);
	}

	public void turnOff() {
		// send an event
		fireEvent(new TurnOffEvent(this));
	}
	
	public static class Clicky implements Runnable {
		private Switch mySwitch;
		private boolean switchIsOn = true;
		
		public Clicky(Switch mySwitch) {
			this.mySwitch = mySwitch;
			
		}
		public void run() {
			if (switchIsOn) {
				mySwitch.turnOff();
				switchIsOn = false;
			} else {
				mySwitch.turnOn();
				switchIsOn = true;
			}
		}
	}
		
}